package com.apexwear.apexutils.ui;


import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.apexwear.apexutils.R;
import com.apexwear.apexutils.common.Constant;
import com.apexwear.apexutils.databinding.ActivityQrBinding;
import com.apexwear.apexutils.model.Device;
import com.apexwear.apexutils.scan.BluetoothScanUtils;
import com.apexwear.apexutils.utils.PermissionUtils;
import com.apexwear.apexutils.utils.ShowToast;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.huawei.hms.hmsscankit.OnLightVisibleCallBack;
import com.huawei.hms.hmsscankit.OnResultCallback;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.hmsscankit.RemoteView;

import java.util.List;


public class QRActivity extends AppCompatActivity {
    final String TAG = this.getClass().getSimpleName();
    final int SCAN_FRAME_SIZE = 240;
    private ActivityQrBinding dataBinding;
    private BluetoothScanUtils bluetoothScanUtils;
    private volatile boolean isDestroy;
    private SweetAlertDialog sweetAlertDialog;
    FinishBroadcast finishBroadcast;
    private String sign;
    private String macAddress;
    private Handler mHandler = new Handler() {
        @SuppressLint("MissingPermission")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x03) {
                BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (!bluetoothAdapter.isEnabled()) {
                    ShowToast.show(QRActivity.this, getString(R.string.open_bluetooth));

                } else {
                    if (bluetoothScanUtils == null) {
                        bluetoothScanUtils = BluetoothScanUtils.getBluetoothScanInstance();
                    }
                    bluetoothScanUtils.startEABleBluetoothScan();
                    Log.e(TAG, "开始查询蓝牙设备");
                    if (mHandler != null && !isDestroy) {
                        mHandler.postDelayed(delayRunnable, 1000);
                    }

                }
            } else if (msg.what == 0x04) {
                //开始绑定手表
                if (sweetAlertDialog == null) {
                    sweetAlertDialog = new SweetAlertDialog(QRActivity.this, SweetAlertDialog.PROGRESS_TYPE);
                    sweetAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                    sweetAlertDialog.setTitleText("Binding...");
                    sweetAlertDialog.setCancelable(false);
                    sweetAlertDialog.setCancelable(false);
                    sweetAlertDialog.setCanceledOnTouchOutside(false);
                }
                if (!sweetAlertDialog.isShowing()) {
                    sweetAlertDialog.show();
                }
                Device device = (Device) msg.obj;
                Intent intent = new Intent(Constant.CONNECT_BROADCAST);
                intent.putExtra("watch_info", device);
                LocalBroadcastManager.getInstance(QRActivity.this).sendBroadcast(intent);
            }
        }
    };
    RemoteView remoteView;
    private Runnable delayRunnable = new Runnable() {
        @Override
        public void run() {
            if (bluetoothScanUtils != null) {
                List<Device> deviceList = bluetoothScanUtils.getDeviceList();
                if (deviceList != null && deviceList.size() > 0) {
                    for (Device device : deviceList) {
                        //   Log.e(TAG,"已经获取到的sn号:"+sign+"已经获取到的蓝牙地址:"+macAddress+",解析出的蓝牙地址:"+device.getAddressTxt());
                        if (!TextUtils.isEmpty(sign)) {
                            if (device.getTagTxt().equalsIgnoreCase(sign)) {
                                isDestroy = true;
                                if (bluetoothScanUtils != null) {
                                    bluetoothScanUtils.stopScan();
                                    bluetoothScanUtils = null;
                                }
                                if (mHandler != null) {
                                    Message message = new Message();
                                    message.what = 0x04;
                                    message.obj = device;
                                    mHandler.sendMessageDelayed(message, 200);
                                }
                                return;
                            }
                        } else if (device.getAddressTxt().equalsIgnoreCase(macAddress)) {
                            isDestroy = true;
                            if (bluetoothScanUtils != null) {
                                bluetoothScanUtils.stopScan();
                                bluetoothScanUtils = null;
                            }
                            if (mHandler != null) {
                                Message message = new Message();
                                message.what = 0x04;
                                message.obj = device;
                                mHandler.sendMessageDelayed(message, 200);
                            }
                            return;
                        }

                    }
                    if (mHandler != null && !isDestroy) {
                        mHandler.postDelayed(delayRunnable, 500);
                    }

                } else {
                    if (mHandler != null && !isDestroy) {
                        mHandler.postDelayed(delayRunnable, 500);
                    }
                }

            }
        }
    };

    @Override
    public void onBackPressed() {
        isDestroy = true;
        if (bluetoothScanUtils != null) {
            bluetoothScanUtils.stopScan();
            bluetoothScanUtils = null;
        }
        super.onBackPressed();
    }

    private void initQr(Bundle savedInstanceState) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        // queryDevice();
        float density = dm.density;
        int mScreenWidth = getResources().getDisplayMetrics().widthPixels;
        int mScreenHeight = getResources().getDisplayMetrics().heightPixels;
        int scanFrameSize = (int) (SCAN_FRAME_SIZE * density);
        Rect rect = new Rect();
        rect.left = mScreenWidth / 2 - scanFrameSize / 2;
        rect.right = mScreenWidth / 2 + scanFrameSize / 2;
        rect.top = mScreenHeight / 2 - scanFrameSize / 2;
        rect.bottom = mScreenHeight / 2 + scanFrameSize / 2;
        remoteView = new RemoteView.Builder().setContext(this).setBoundingBox(rect).setFormat(HmsScan.QRCODE_SCAN_TYPE).build();
        remoteView.setOnLightVisibleCallback(new OnLightVisibleCallBack() {
            @Override
            public void onVisibleChanged(boolean visible) {
                if (visible) {
                }
            }
        });
        remoteView.setOnResultCallback(new OnResultCallback() {
            @SuppressLint("MissingPermission")
            @Override
            public void onResult(HmsScan[] result) {
                if (result != null && result.length > 0 && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) {
                    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                    vibrator.vibrate(200);
                    remoteView.onStop();
                    String scanResult = result[0].getOriginalValue();
                    if (!TextUtils.isEmpty(scanResult)) {
                        Log.e(TAG, "扫描出来的数据:" + scanResult);
                        if (scanResult.contains("?")) {
                            String param = scanResult.split("\\?")[1];
                            if (!TextUtils.isEmpty(param)) {
                                if (param.contains("&")) {
                                    String[] sn = param.split("&");
                                    if (sn != null) {
                                        for (int i = 0; i < sn.length; i++) {
                                            if (sn[i].contains("=")) {
                                                String[] tempSn = sn[i].split("=");
                                                if (tempSn != null) {
                                                    String snKey = tempSn[0];
                                                    if (!TextUtils.isEmpty(snKey) && snKey.equalsIgnoreCase("SN")) {
                                                        sign = tempSn[1];
                                                        Log.e(TAG, "解析出来的SN号:" + sign);
                                                        if (mHandler != null && !isDestroy) {
                                                            mHandler.sendEmptyMessage(0x03);
                                                        }
                                                        break;
                                                    } else if (!TextUtils.isEmpty(snKey) && snKey.equalsIgnoreCase("mac")) {
                                                        macAddress = tempSn[1].toUpperCase();
                                                        Log.e(TAG, "扫描出的蓝牙地址:" + macAddress);
                                                        if (mHandler != null) {
                                                            mHandler.sendEmptyMessage(0x03);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    if (param.contains("=")) {
                                        String[] pString = param.split("=");
                                        if (pString.length >= 2) {
                                            if ("mac".equalsIgnoreCase(pString[0]) && BluetoothAdapter.checkBluetoothAddress(pString[1])) {
                                                macAddress = pString[1].toUpperCase();
                                                Log.e(TAG, "扫描出的蓝牙地址:" + macAddress);
                                                if (mHandler != null) {
                                                    mHandler.sendEmptyMessage(0x03);
                                                }

                                            } else if ("sn".equalsIgnoreCase(pString[0])) {
                                                sign = pString[1];
                                                Log.e(TAG, "解析出来的SN号:" + sign);
                                                if (mHandler != null && !isDestroy) {
                                                    mHandler.sendEmptyMessage(0x03);
                                                }

                                            } else {
                                                Log.i(TAG, "Invalid parameter");
                                            }
                                        }
                                    }else{
                                        if (BluetoothAdapter.checkBluetoothAddress(param)) {
                                            macAddress = param.toUpperCase();
                                            Log.e(TAG, "扫描出的蓝牙地址:" + macAddress);
                                            if (mHandler != null) {
                                                mHandler.sendEmptyMessage(0x03);
                                            }

                                        } else{
                                            Log.i(TAG, "Invalid parameter");
                                        }
                                    }
                                }
                            }
                        } else {

                            //将数据转换成蓝牙地址
                            boolean isBluetooth = BluetoothAdapter.checkBluetoothAddress(scanResult);
                            if (!isBluetooth) {
                                //将地址转换成标准的蓝牙地址
                                StringBuffer sb = new StringBuffer(scanResult);
                                int index = 2;
                                int count = 2;
                                while (sb.length() > count && index < sb.length() - 1) {
                                    sb.insert(index, ":");
                                    index += 3;
                                }
                                scanResult = sb.toString();
                            }
                            macAddress = scanResult;
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x03);
                            }


                        }

                    }

                }
            }
        });
        remoteView.onCreate(savedInstanceState);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        dataBinding.cameraShow.addView(remoteView, params);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_qr);
        dataBinding.searchBle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isDestroy = true;
                Intent intent = new Intent(QRActivity.this, ManualScanningActivity.class);
                startActivity(intent);
                finish();
            }
        });

        dataBinding.tooBar.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(dataBinding.tooBar);
        getSupportActionBar().setTitle(null);
        initQr(savedInstanceState);
        dataBinding.tooBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "退出当前页面");
                isDestroy = true;
                if (bluetoothScanUtils != null) {
                    bluetoothScanUtils.stopScan();
                    bluetoothScanUtils = null;
                }
                finish();
            }
        });
        if (finishBroadcast == null) {
            finishBroadcast = new FinishBroadcast();
            LocalBroadcastManager.getInstance(this).registerReceiver(finishBroadcast, new IntentFilter(Constant.CONNECT_STATE_BROADCAST));

        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        remoteView.onStart();

    }

    @Override
    protected void onResume() {
        super.onResume();
        remoteView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        remoteView.onPause();
    }

    @Override
    protected void onStop() {
        remoteView.onStop();
        super.onStop();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    protected void onDestroy() {
        isDestroy = true;
        remoteView.onDestroy();
        if (finishBroadcast != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(finishBroadcast);
            finishBroadcast = null;
        }
        if (sweetAlertDialog != null) {
            sweetAlertDialog.dismiss();
            sweetAlertDialog = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        delayRunnable = null;
        bluetoothScanUtils = null;
        if (dataBinding != null) {
            dataBinding.unbind();
            dataBinding = null;
        }
        super.onDestroy();
    }

    class FinishBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action)) {
                if (action.equalsIgnoreCase(Constant.CONNECT_STATE_BROADCAST)) {
                    if (sweetAlertDialog != null) {
                        sweetAlertDialog.dismiss();
                    }
                    boolean state = intent.getBooleanExtra("connect_state", false);
                    if (state) {
                        isDestroy = true;
                        finish();
                    } else {
                        ShowToast.show(QRActivity.this, getString(R.string.failed_to_bind_the_watch));
                    }
                }
            }
        }
    }
}
